{
  "cells": [
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "d4KCUoxSpdoZ"
      },
      "outputs": [],
      "source": [
        "BRANCH = 'main'\n",
        "\n",
        "\"\"\"\n",
        "You can run either this notebook locally (if you have all the dependencies and a GPU) or on Google Colab.\n",
        "\n",
        "Instructions for setting up Colab are as follows:\n",
        "1. Open a new Python 3 notebook.\n",
        "2. Import this notebook from GitHub (File -> Upload Notebook -> \"GITHUB\" tab -> copy/paste GitHub URL)\n",
        "3. Connect to an instance with a GPU (Runtime -> Change runtime type -> select \"GPU\" for hardware accelerator)\n",
        "4. Run this cell to set up dependencies.\n",
        "\"\"\""
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "JDk9zxC6pdod"
      },
      "outputs": [],
      "source": [
        "import os\n",
        "# either provide a path to local NeMo repository with NeMo already installed or git clone\n",
        "\n",
        "# option #1: local path to NeMo repo with NeMo already installed\n",
        "NEMO_DIR_PATH = \"NeMo\"\n",
        "\n",
        "# option #2: download NeMo repo\n",
        "if 'google.colab' in str(get_ipython()) or not os.path.exists(NEMO_DIR_PATH):\n",
        "  ! git clone -b $BRANCH https://github.com/NVIDIA/NeMo\n",
        "  ! cd NeMo\n",
        "  ! python -m pip install git+https://github.com/NVIDIA/NeMo.git@$BRANCH#egg=nemo_toolkit[all]"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "CH7yR7cSwPKr"
      },
      "outputs": [],
      "source": [
        "import json\n",
        "import os\n",
        "import wget\n",
        "\n",
        "from IPython.display import Audio\n",
        "import numpy as np\n",
        "import scipy.io.wavfile as wav\n",
        "\n",
        "! pip install pandas\n",
        "! pip install plotly\n",
        "from plotly import graph_objects as go"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xXRARM8XtK_g"
      },
      "source": [
        "# 1. Introduction\n",
        "End-to-end Automatic Speech Recognition (ASR) systems surpassed traditional systems in performance but require large amounts of labeled data for training. \n",
        "\n",
        "This tutorial will show how to use a pre-trained with Connectionist Temporal Classification (CTC) ASR model, such as [QuartzNet Model](https://arxiv.org/abs/1910.10261) or [Citrinet](https://arxiv.org/abs/2104.01721) to split long audio files and the corresponding transcripts into shorter fragments that are suitable for an ASR model training. \n",
        "\n",
        "We're going to use [ctc-segmentation](https://github.com/lumaku/ctc-segmentation) Python package based on the algorithm described in [CTC-Segmentation of Large Corpora for German End-to-end Speech Recognition](https://arxiv.org/pdf/2007.09127.pdf)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "8FAZKakrIyGI"
      },
      "outputs": [],
      "source": [
        "requirements = f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/tools/ctc_segmentation/requirements.txt'\n",
        "wget.download(requirements)\n",
        "! pip install -r requirements.txt\n",
        "! apt-get install -y ffmpeg\n",
        "! apt-get install -y libsox-fmt-mp3 "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "S1DZk-inQGTI"
      },
      "source": [
        "`TOOLS_DIR` contains scripts that we are going to need during the next steps, all necessary scripts could be found [here](https://github.com/NVIDIA/NeMo/tree/main/tools/ctc_segmentation/scripts)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1C9DdMfvRFM-"
      },
      "outputs": [],
      "source": [
        "if 'google.colab' in str(get_ipython()):\n",
        "  NEMO_DIR_PATH = \"/content/NeMo\"\n",
        "elif not os.path.exists(NEMO_DIR_PATH):\n",
        "  NEMO_DIR_PATH = \"NeMo\"\n",
        "    \n",
        "TOOLS_DIR = f'{NEMO_DIR_PATH}/tools/ctc_segmentation/scripts'\n",
        "print(TOOLS_DIR)\n",
        "! ls -l $TOOLS_DIR"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XUEncnqTIzF6"
      },
      "source": [
        "# 2. Data Download\n",
        "First, let's download audio and text data (data source: [https://librivox.org/](https://librivox.org/) and [http://www.gutenberg.org](http://www.gutenberg.org)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bkeKX2I_tIgV"
      },
      "outputs": [],
      "source": [
        "## create data directory and download an audio file\n",
        "WORK_DIR = 'WORK_DIR'\n",
        "DATA_DIR = WORK_DIR + '/DATA'\n",
        "os.makedirs(DATA_DIR, exist_ok=True)\n",
        "\n",
        "print('downloading audio samples...')\n",
        "wget.download(\"https://multilangaudiosamples.s3.us-east-2.amazonaws.com/audio_samples.zip\", DATA_DIR)\n",
        "! unzip -o $DATA_DIR/audio_samples.zip -d $DATA_DIR\n",
        "! rm $DATA_DIR/audio_samples.zip\n",
        "\n",
        "DATA_DIR = os.path.join(DATA_DIR, \"audio_samples\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2JAv7ePmpdok"
      },
      "source": [
        "We downloaded audio and text samples in `English` and `Spanish`:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Y6VYVk9mpdol"
      },
      "outputs": [],
      "source": [
        "! ls $DATA_DIR"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-_XE9MkKuAA7"
      },
      "source": [
        "Data folder for each language contains both audio and text files. Note, the text file and the audio file share the same base name. For example, an audio file `example.wav` should have a corresponding text file called `example.txt`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IGhijb-Bpdol"
      },
      "outputs": [],
      "source": [
        "! ls $DATA_DIR/es/audio/ $DATA_DIR/es/text/"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FWqlbSryw_WL"
      },
      "source": [
        "# 3. Segmentation of a single file (Spanish sample)\n",
        "\n",
        "Let's listen to our Spanish audio sample:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ulkPrqwipdom"
      },
      "outputs": [],
      "source": [
        "base_name_es = \"el19demarzoyel2demayo_03_perezgaldos\"\n",
        "Audio(f\"{DATA_DIR}/es/audio/{base_name_es}.wav\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RzlLsmMXpdom"
      },
      "source": [
        "Let's take a look at the ground truth text:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9Qfp10Xnpdom"
      },
      "outputs": [],
      "source": [
        "text = f\"{DATA_DIR}/es/text/{base_name_es}.txt\"\n",
        "! cat $text"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RMT5lkPYzZHK"
      },
      "source": [
        "As one probably noticed, the audio file contains a prologue and an epilogue that are missing in the corresponding text. The segmentation algorithm could handle extra audio fragments at the end and the beginning of the audio, but prolonged untranscribed audio segments in the middle of the file could deteriorate segmentation results. That is why, it is recommended to normalize text, so that transcripts contain spoken equivalents of abbreviations and numbers.\n",
        "\n",
        "## 3.1. Prepare Text and Audio\n",
        "\n",
        "We're going to use `prepare_data.py` script to prepare both text and audio data for segmentation.\n",
        "\n",
        "### Text preprocessing:\n",
        "* the text will be roughly split into sentences and stored under '$OUTPUT_DIR/processed/*.txt' where each sentence is going to start with a new line (we're going to find alignments for these sentences in the next steps)\n",
        "* to change the lengths of the final sentences/fragments, specify additional punctuation marks to split the text into fragments, use `--additional_split_symbols` argument. Use `|` as a separator between symbols, for example: `--additional_split_symbols=;|:`\n",
        "* `max_length` argument - max number of words in a segment for alignment (used only if there are no punctuation marks present in the original text. Long non-speech segments are better for segments split and are more likely to co-occur with punctuation marks. Random text split could deteriorate the quality of the alignment.\n",
        "* out-of-vocabulary words will be removed based on pre-trained ASR model vocabulary, and the text will be changed to lowercase \n",
        "* sentences for alignment with the original punctuation and capitalization will be stored under  `$OUTPUT_DIR/processed/*_with_punct.txt`\n",
        "* numbers will be converted from written to their spoken form with `num2words` package. For English, it's recommended to use NeMo normalization tool use `--use_nemo_normalization` argument (not supported if running this segmentation tutorial in Colab, see the text normalization tutorial: [`https://github.com/NVIDIA/NeMo-text-processing/blob/main/tutorials/Text_(Inverse)_Normalization.ipynb`](https://colab.research.google.com/github/NVIDIA/NeMo-text-processing/blob/main/tutorials/Text_(Inverse)_Normalization.ipynb) for more details). Even `num2words` normalization is usually enough for proper segmentation. However, it does not take audio into account. NeMo supports audio-based normalization for English, German and Russian languages that can be applied to the segmented data as a post-processing step. Audio-based normalization produces multiple normalization options. For example, `901` could be normalized as `nine zero one` or `nine hundred and one`. The audio-based normalization chooses the best match among the possible normalization options and the transcript based on the character error rate. See [https://github.com/NVIDIA/NeMo-text-processing/blob/main/nemo_text_processing/text_normalization/normalize_with_audio.py](https://github.com/NVIDIA/NeMo-text-processing/blob/main/nemo_text_processing/text_normalization/normalize_with_audio.py) for more details.\n",
        "\n",
        "### Audio preprocessing:\n",
        "* non '.wav' audio files will be converted to `.wav` format\n",
        "* audio files will be resampled to 16kHz (sampling rate used during training NeMo ASR models)\n",
        "* stereo tracks will be converted to mono\n",
        "* In some cases, if an audio contains a very long untranscribed prologue, increasing `--cut_prefix` value might help improve segmentation quality.\n",
        "\n",
        "\n",
        "The `prepare_data.py` will preprocess all `.txt` files found in the `--in_text=$DATA_DIR` and all audio files located at `--audio_dir=$DATA_DIR`.\n",
        "\n",
        "We are going to use [Spanish Citrinet-512 model](https://catalog.ngc.nvidia.com/orgs/nvidia/teams/nemo/models/stt_es_citrinet_512)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "u4zjeVVv-UXR"
      },
      "outputs": [],
      "source": [
        "MODEL = \"stt_es_citrinet_512\" \n",
        "OUTPUT_DIR = WORK_DIR + \"/es_output\"\n",
        "\n",
        "! rm -rf $OUTPUT_DIR\n",
        "\n",
        "! python $TOOLS_DIR/prepare_data.py \\\n",
        "--in_text=$DATA_DIR/es/text \\\n",
        "--output_dir=$OUTPUT_DIR/processed/ \\\n",
        "--language='en' \\\n",
        "--model=$MODEL \\\n",
        "--audio_dir=$DATA_DIR/es/audio"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kmDTCuTLH7pm"
      },
      "source": [
        "The following four files should be generated and stored at the `$OUTPUT_DIR/processed` folder:\n",
        "\n",
        "* el19demarzoyel2demayo_03_perezgaldos.txt (lower cased and normalized text with punctuation removed, each line represents an utterance for alignment)\n",
        "* el19demarzoyel2demayo_03_perezgaldos.wav (.wav mono file, 16kHz)\n",
        "* el19demarzoyel2demayo_03_perezgaldos_with_punct.txt  (raw utterances for alignment with punctuation and case preserved)\n",
        "* el19demarzoyel2demayo_03_perezgaldos_with_punct_normalized.txt (normalized utterances for alignment utterance for alignment with punctuation and case preserved)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6R7OKAsYH9p0"
      },
      "outputs": [],
      "source": [
        "! ls $OUTPUT_DIR/processed"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "bIvKBwRcH_9W"
      },
      "source": [
        "The `.txt` file without punctuation contains preprocessed text phrases that we're going to align within the audio file. Here, we split the text into sentences. Each line should contain a text snippet for alignment."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "74GLpMgoICmk"
      },
      "outputs": [],
      "source": [
        "! head $OUTPUT_DIR/processed/el19demarzoyel2demayo_03_perezgaldos.txt"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QrvZAjeoR9U1"
      },
      "source": [
        "## 3.2. Run CTC-Segmentation\n",
        "\n",
        "In this step, we're going to use the [`ctc-segmentation`](https://github.com/lumaku/ctc-segmentation) to find the start and end time stamps for the segments we created during the previous step.\n",
        "\n",
        "\n",
        "As described in the [CTC-Segmentation of Large Corpora for German End-to-end Speech Recognition](https://arxiv.org/pdf/2007.09127.pdf), the algorithm is relying on a CTC-based ASR model to extract utterance segments with exact time-wise alignments. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xyKtaqAd-Tvk"
      },
      "outputs": [],
      "source": [
        "WINDOW = 8000\n",
        "\n",
        "! python $TOOLS_DIR/run_ctc_segmentation.py \\\n",
        "--output_dir=$OUTPUT_DIR \\\n",
        "--data=$OUTPUT_DIR/processed \\\n",
        "--model=$MODEL \\\n",
        "--window_len=$WINDOW "
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "wY27__e3HmhH"
      },
      "source": [
        "`WINDOW` parameter might need to be adjusted depending on the length of the utterance one wants to align, the default value should work in most cases. By default, if the alignment is not found for the initial `WINDOW` size, the window size will be doubled a few times to re-try backtracing. \n",
        "\n",
        "Let's take a look at the generated alignments."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ktBAsfJRVCwI"
      },
      "outputs": [],
      "source": [
        "alignment_file = f\"{WINDOW}_{base_name_es}_segments.txt\"\n",
        "! head -n 3 $OUTPUT_DIR/segments/$alignment_file"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xCwEFefHZz1C"
      },
      "source": [
        "The expected output for our audio sample looks like this:\n",
        "\n",
        "```\n",
        "<PATH_TO>/processed/el19demarzoyel2demayo_03_perezgaldos.wav\n",
        "11.518331881862931 25.916246734191596 -1.2629864680237006 | entraron en la habitación donde estábamos y al punto que d mauro vio a su sobrina dirigiose a ella con los brazos abiertos y al estrecharla en ellos exclamó endulzando la voz ¡inés de mi alma inocente hija de mi prima juana | Entraron en la habitación donde estábamos, y al punto que D.  Mauro vio a su sobrina dirigiose a ella con los brazos abiertos, y al estrecharla en ellos, exclamó endulzando la voz: -¡Inés de mi alma, inocente hija de mi prima Juana! | Entraron en la habitación donde estábamos, y al punto que D.  Mauro vio a su sobrina dirigiose a ella con los brazos abiertos, y al estrecharla en ellos, exclamó endulzando la voz: - Inés de mi alma, inocente hija de mi prima Juana!\n",
        "25.756269902499053 28.155922377887165 -0.0003830735786323203 | al fin al fin te veo | Al fin, al fin te veo. | Al fin, al fin te veo.\n",
        "...\n",
        "```\n",
        "\n",
        "**Details of the file content**:\n",
        "- the first line of the file contains the path to the original audio file\n",
        "- all subsequent lines contain:\n",
        "  * the first number is the start of the segment (in seconds)\n",
        "  * the second one is the end of the segment (in seconds)\n",
        "  * the third value - alignment confidence score (in log space)\n",
        "  * text fragments corresponding to the timestamps\n",
        "  * original text without pre-processing\n",
        "  * normalized text\n",
        "\n",
        "Finally, we're going to split the original audio file into segments based on the found alignments. We're going to save only segments with alignment score above the threshold value (default threshold=-2:\n",
        "* high scored clips (segments with the segmentation score above the threshold value)\n",
        "* low scored clips (segments with the segmentation score below the threshold)\n",
        "* deleted segments (segments that were excluded during the alignment. For example, in our sample audio file, the prologue and epilogue that don't have the corresponding transcript were excluded. Oftentimes, deleted files also contain such things as clapping, music, or hard breathing. \n",
        "\n",
        "The alignment score values depend on the pre-trained model quality and the dataset.\n",
        "\n",
        "Also note, that the `OFFSET` parameter is something one might want to experiment with since timestamps have a delay (offset) depending on the model.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6YM64RPlitPL"
      },
      "outputs": [],
      "source": [
        "OFFSET = 0\n",
        "THRESHOLD = -2\n",
        "\n",
        "! python $TOOLS_DIR/cut_audio.py \\\n",
        "--output_dir=$OUTPUT_DIR \\\n",
        "--alignment=$OUTPUT_DIR/segments/ \\\n",
        "--threshold=$THRESHOLD \\\n",
        "--offset=$OFFSET"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QoyS0T8AZxcx"
      },
      "source": [
        "## 3.3. Transcribe segmented audio\n",
        "\n",
        "The transcripts will be saved in a new manifest file in `pred_text` field."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1UaSIflBZwaV"
      },
      "outputs": [],
      "source": [
        "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/asr/transcribe_speech.py')\n",
        "\n",
        "! python transcribe_speech.py \\\n",
        "pretrained_name=$MODEL \\\n",
        "dataset_manifest=$OUTPUT_DIR/manifests/manifest.json \\\n",
        "output_filename=$OUTPUT_DIR/manifests/manifest_transcribed.json"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "F-nPT8z_IVD-"
      },
      "outputs": [],
      "source": [
        "def plot_signal(signal, sample_rate):\n",
        "    \"\"\" Plot the signal in time domain \"\"\"\n",
        "    fig_signal = go.Figure(\n",
        "        go.Scatter(x=np.arange(signal.shape[0])/sample_rate,\n",
        "                   y=signal, line={'color': 'green'},\n",
        "                   name='Waveform',\n",
        "                   hovertemplate='Time: %{x:.2f} s<br>Amplitude: %{y:.2f}<br><extra></extra>'),\n",
        "        layout={\n",
        "            'height': 200,\n",
        "            'xaxis': {'title': 'Time, s'},\n",
        "            'yaxis': {'title': 'Amplitude'},\n",
        "            'title': 'Audio Signal',\n",
        "            'margin': dict(l=0, r=0, t=40, b=0, pad=0),\n",
        "        }\n",
        "    )\n",
        "    fig_signal.show()\n",
        "    \n",
        "def display_samples(manifest):\n",
        "    \"\"\" Display audio and reference text.\"\"\"\n",
        "    with open(manifest, 'r') as f:\n",
        "        for line in f:\n",
        "            sample = json.loads(line)\n",
        "            sample_rate, signal = wav.read(sample['audio_filepath'])\n",
        "            plot_signal(signal, sample_rate)\n",
        "            display(Audio(sample['audio_filepath']))\n",
        "            display('Reference text:       ' + sample['text_no_preprocessing'])\n",
        "            if 'pred_text' in sample:\n",
        "                display('ASR transcript: ' + sample['pred_text'])\n",
        "            print(f\"Score: {sample['score']}\")\n",
        "            print('\\n' + '-' * 110)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "S69UFA30ZvxV"
      },
      "source": [
        "Let's examine the high scored segments we obtained.\n",
        "\n",
        "The `Reference text` in the next cell represents the original text without pre-processing, while `ASR transcript` is an ASR model prediction with greedy decoding. Also notice, that `ASR transcript` in some cases contains errors that could decrease the alignment score, but usually it doesn’t hurt the quality of the aligned segments.\n",
        "\n",
        "Displaying audio in Jupyter Notebook could be slow, it's recommended to use [Speech Data Explorer](https://docs.nvidia.com/deeplearning/nemo/user-guide/docs/en/stable/tools/speech_data_explorer.html) to analyze speech data."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "Q45uBtsHIaAD"
      },
      "outputs": [],
      "source": [
        "# let's examine only a few first samples\n",
        "! head -n 2 $OUTPUT_DIR/manifests/manifest_transcribed.json > $OUTPUT_DIR/manifests/samples.json\n",
        "\n",
        "display_samples(f\"{OUTPUT_DIR}/manifests/samples.json\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "yivXpD25T4Ir"
      },
      "source": [
        "# 4. Processing of multiple files (English samples)\n",
        "\n",
        "Up until now, we were processing only one file at a time, but to create a large dataset processing of multiple files simultaneously could help speed up things considerably. \n",
        "\n",
        "Our English data folder contains 2 audio files and corresponding text files:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "KRc9yMjPXPgj"
      },
      "outputs": [],
      "source": [
        "! ls $DATA_DIR/en/audio $DATA_DIR/en/text"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3ftilXu-5tzT"
      },
      "source": [
        "We are going to use `run_segmentation.sh` to perform all the above steps starting from the text and audio preprocessing to segmentation and manifest creation in a single step:"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2I4w34Hepdor"
      },
      "source": [
        "`run_segmentation.sh` script takes `DATA_DIR` argument and assumes that it contains folders `text` and `audio`.\n",
        "An example of the `DATA_DIR` folder structure:\n",
        "\n",
        "\n",
        "--DATA_DIR\n",
        "\n",
        "     |----audio\n",
        "            |---1.mp3\n",
        "            |---2.mp3\n",
        "            \n",
        "     |-----text\n",
        "            |---1.txt\n",
        "            |---2.txt"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nYXNvBDsHMEu"
      },
      "source": [
        "`run_segmentation.sh` could use multiple `WINDOW` sizes for segmentation, and then adds segments that were similarly aligned with various window sizes to `verified_segments` folder. This could be useful to reduce the amount of manual work while checking the alignment quality."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "hRFAl0gO92bp"
      },
      "outputs": [],
      "source": [
        "MODEL = \"QuartzNet15x5Base-En\" # \"stt_en_citrinet_512_gamma_0_25\" \n",
        "OUTPUT_DIR_2 = WORK_DIR + \"/en_output\"\n",
        "\n",
        "! rm -rf $OUTPUT_DIR_2\n",
        "\n",
        "! bash $TOOLS_DIR/../run_segmentation.sh \\\n",
        "--MODEL_NAME_OR_PATH=$MODEL \\\n",
        "--DATA_DIR=$DATA_DIR/en \\\n",
        "--OUTPUT_DIR=$OUTPUT_DIR_2 \\\n",
        "--SCRIPTS_DIR=$TOOLS_DIR \\\n",
        "--MIN_SCORE=$THRESHOLD  \\\n",
        "--USE_NEMO_NORMALIZATION=False"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "zzJTwKq2Kl9U"
      },
      "source": [
        "Manifest file with segments with alignment score above the threshold values are saved in `en/output/manifests/manifest.json`.\n",
        "\n",
        "Next, we are going to run `run_filter.sh`. The script does the following:\n",
        "* adds ASR transcripts to the manifest\n",
        "* calculates and saves metrics such as Word Error Rate (WER), Character Error Rate (CER), CER at the tails of the audio file, word difference between reference and transcript, mean absolute values at the tails of the audio.\n",
        "* filters out samples that do not satisfy threshold values and saves selected segments in `manifest_transcribed_metrics_filtered.json`.\n",
        "\n",
        "Note, it's better to analyze the manifest with metrics in Speech Data Explorer to decide on what thresholds should be used for final sample selection."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xsm89hYlpdor"
      },
      "outputs": [],
      "source": [
        "! bash $TOOLS_DIR/../run_filter.sh \\\n",
        "--SCRIPTS_DIR=$TOOLS_DIR \\\n",
        "--MODEL_NAME_OR_PATH=stt_en_conformer_ctc_large \\\n",
        "--MANIFEST=$OUTPUT_DIR_2/manifests/manifest.json \\\n",
        "--INPUT_AUDIO_DIR=$DATA_DIR/en/audio/"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "nacE_iQ2_85L"
      },
      "outputs": [],
      "source": [
        "# let's examine only a few first samples\n",
        "! head -n 2 $OUTPUT_DIR_2/manifests/manifest_transcribed_metrics_filtered.json > $OUTPUT_DIR_2/manifests/samples.json\n",
        "\n",
        "display_samples(f\"{OUTPUT_DIR_2}/manifests/samples.json\")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lcvT3P2lQ_GS"
      },
      "source": [
        "# Next Steps\n",
        "\n",
        "- Check out [NeMo Speech Data Explorer tool](https://github.com/NVIDIA/NeMo/tree/main/tools/speech_data_explorer#speech-data-explorer) to interactively evaluate the aligned segments.\n",
        "- Try Audio-based normalization tool."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GYylwvTX2VSF"
      },
      "source": [
        "# References\n",
        "Kürzinger, Ludwig, et al. [\"CTC-Segmentation of Large Corpora for German End-to-End Speech Recognition.\"](https://arxiv.org/abs/2007.09127) International Conference on Speech and Computer. Springer, Cham, 2020."
      ]
    }
  ],
  "metadata": {
    "accelerator": "GPU",
    "colab": {
      "collapsed_sections": [],
      "name": "CTC_Segmentation_Tutorial_update.ipynb",
      "private_outputs": true,
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3 (ipykernel)",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.9.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
